var WxParse = require('../../wxParse/wxParse.js');
//获取应用实例
var app = getApp()
Page({
  data: {
    showLoading: true,
    noMoretip: false,
    page: 0,
    isSettled:0,
    showLocationtip: false,
    locationTips: '正在定位中，请耐心等待~',
    curType:'new'
  },
  onLoad:function(e){
    var that = this;
    if (e && e.enterfrom) {
      var enterfrom = e.enterfrom == 'share' ? true : false;
      that.setData({
        enterfrom: enterfrom
      })
    }
    var location = app.globalData.location;
    if (location && location.lat) {
      that.setData({
        curChooseLatitude: location.lat,
        curChooseLongitude: location.lng
      })
      that.requestShoplist();
    } else {
      that.getLocation();
    }
    app.requestAd(that);
  },
  onShow: function () {
    var that = this;
    if (that.data.title) { 
      app.setNavtitle(that.data.title);
    }
    if (!app.globalData.plumSession) {
      console.log("暂未获取到session");
      app.wechatSq(that);
    } else {
      that.resuestTelIndexinfo();
    }
    app.setCartnum();//更新购物车数量
  },
  resuestTelIndexinfo:function() {
    var that = this;
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: app.globalData.requestUrl,
      data: {
        map: 'applet_mobile_index'
      },
      success: function (res) {
        if (res.data.ec == 200) {
          console.log(res.data.data);
          that.setData({
            telIndexinfo: res.data.data,
            title: res.data.data.title,
            isSettled: res.data.data.isenter
          })
          app.globalData.agreement = res.data.data.agreement;
          app.globalData.isSettled = res.data.data.isSettled;
          if (res.data.data.title){
            app.setNavtitle(res.data.data.title);
          }else{
            app.setNavtitle("电话本");
          }
          that.getRect();
        } else {
          console.log(res.data)
          app.errorTip(that, res.data.em, 2000);
        }
      },
      complete: function () {
        wx.hideLoading();
      }
    });
  },
  toggleType: function (e) {
    var that = this;
    var type = e.currentTarget.dataset.type;
    that.setData({
      curType: type,
      page: 0
    })
    that.requestShoplist();
  },
  requestShoplist: function (name) {
    var that = this;
    var data = {};
    var isKeyword = that.data.isKeyword ? that.data.isKeyword:false;
    var page = that.data.page;
    data.map = 'applet_mobile_shop_list';
    data.sort = that.data.curType;
    data.cate = '';
    data.page = page;
    data.lng = that.data.curChooseLongitude ? that.data.curChooseLongitude : 0;
    data.lat = that.data.curChooseLatitude ? that.data.curChooseLatitude : 0;
    if (isKeyword) {
      data.cate = '';
      if (name) {
        data.name = name;
      }
    }
    console.log(data);
    wx.request({
      url: app.globalData.requestUrl,
      data: data,
      success: function (res) {
        console.log(page);
        console.log(res.data);
        if (res.data.ec == 200) {
          var allArr = [];
          var initArr = that.data.shopList ? that.data.shopList : [];
          var curArr = res.data.data;
          var lastPageLength = curArr.length;
          if (page > 0) {
            allArr = initArr.concat(curArr);
          } else {
            allArr = res.data.data;
          }
          that.setData({
            shopList: allArr,
            searchTxt: ''
          })
          if (lastPageLength < 10) {
            that.setData({
              noMoretip: true,
              showLoading: false
            });
          }
          console.log(that.data.shopList);
        } else {
          if (page <= 0) {
            that.setData({
              shopList: [],
              noMoretip: false,
              showLoading: false
            })
          } else {
            that.setData({
              noMoretip: true,
              showLoading: false
            });
          }
        }
      },
      complete: function () {
        wx.stopPullDownRefresh();
      }
    });
  },
  getLocation: function (e) {
    var that = this;
    that.setData({
      showLocationtip: true
    })
    wx.getLocation({
      success: function (res) {
        console.log(res);
        that.setData({
          curChooseLatitude: res.latitude,
          curChooseLongitude: res.longitude,
          showLocationtip: false
        })
        var location = {
          lat: res.latitude,
          lng: res.longitude
        }
        app.globalData.location = location;
        that.requestShoplist();
      },
      fail: function () {
        wx.getSetting({
          success: (res) => {
            if (res.authSetting['scope.userLocation']) {
              that.setData({
                locationTips: "无法获取您的当前定位地址，请打开定位权限"
              })
            } else {
              wx.openSetting({
                success: (res) => {
                  res.authSetting = {
                    "scope.userLocation": true
                  }
                  console.log(res.authSetting);
                  that.onPullDownRefresh();
                }
              })
            }
          }
        })
      },
      complete: function () {
        // wx.hideLoading(); 
      }
    })
  },
  chooseLocation: function () {
    var that = this;
    wx.chooseLocation({
      success: (res) => {
        console.log(res);
        var curLocation = res.name ? res.name : res.address;
        that.setData({
          curLocation: curLocation,
          curChooseLatitude: res.latitude,
          curChooseLongitude: res.longitude,
          curShopCategory: '',
          showLocationtip: false
        })
        var location = {
          lat: res.latitude,
          lng: res.longitude
        }
        app.globalData.location = location;
        that.requestShoplist();
      },
      fail: (res) => {
        wx.getSetting({
          success: (res) => {
            if (res.authSetting['scope.userLocation']) {
              that.setData({
                locationTips: "无法获取您的当前定位地址，请打开定位权限"
              })
            } else {
              wx.openSetting({
                success: (res) => {
                  res.authSetting = {
                    "scope.userLocation": true
                  }
                  console.log(res.authSetting);
                  that.onPullDownRefresh();
                }
              })
            }
          }
        })
      }
    })
  },
  onPullDownRefresh: function () {
    var that = this;
    that.setData({
      page: 0,
      noMoretip: false,
      showLoading: true
    });
    that.onLoad();
    that.resuestTelIndexinfo();
  },
  onReachBottom: function () {
    var that = this;
    console.log("到达页面底部")
    var isMore = that.data.noMoretip;
    var page = that.data.page;
    page++;
    that.setData({
      page: page
    });
    if (isMore) {
      console.log("已完成或正在加载");
    } else {
      that.requestShoplist();
    }
  },
  // 监听页面滚动
  onPageScroll:function(e){
    var that = this;
    var scrollTop = e.scrollTop;
    var topPartH = that.data.topPartH;
    if (scrollTop >= topPartH && that.data.fixedTab!=1){
      that.setData({ fixedTab: 1 })
    } else if (scrollTop < topPartH && that.data.fixedTab != 0){
      that.setData({ fixedTab: 0 })
    }
  },
  getRect: function () {
    var that = this;
    wx.createSelectorQuery().select('#topPart').boundingClientRect(function (rect) {
      that.setData({
        topPartH: rect.height
      })
    }).exec()
  },
  // 查看地图
  openMap: function (e) {
    var latitude = e.currentTarget.dataset.lat;
    var longitude = e.currentTarget.dataset.lng;
    var address = e.currentTarget.dataset.address;
    var name = e.currentTarget.dataset.name;
    wx.openLocation({
      latitude: Number(latitude),
      longitude: Number(longitude),
      name: name,
      address: address,
      scale: 18
    })
  },
  // 拨打电话
  makeCall: function (e) {
    var that = this;
    var mobile = e.currentTarget.dataset.mobile;
    var id = e.currentTarget.dataset.id;
    wx.showModal({
      title: '',
      content: '拨打电话 ' + mobile,
      confirmText: '拨打',
      confirmColor: '#48C23D',
      success: function (res) {
        if (res.confirm) {
          wx.makePhoneCall({
            phoneNumber: mobile,
            success: function () {
              that.requestCall(id);
            },
            fail: function () {
              console.log("拨打电话失败！")

            }
          })
        }
      }
    })
  },
  toTelcategory:function(){
    wx.navigateTo({
      url: '/subpages/telcategory/telcategory',
    })
  },
  toMycollect: function (e) {
    var type = e.currentTarget.dataset.type;
    wx.navigateTo({
      url: '/subpages/myCollect/myCollect?type='+type,
    })
  },
  toShopInfoDetail:function(e){
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/subpages/shopInfoDetail/shopInfoDetail?id=' + id,
    })
  },
  toshopTelsettled:function(){
    var that = this;
    var isSettled = that.data.isSettled;
    if(isSettled==0){
      wx.navigateTo({
        url: '/subpages/shopTelsettled/shopTelsettled',
      })
    }else{
      wx.navigateTo({
        url: '/subpages/mySettledshop/mySettledshop',
      })
    }
  },
  toShopinfolist: function (e) {
    var title = e.currentTarget.dataset.title;
    wx.navigateTo({
      url: '/subpages/shopInfoList/shopInfoList?title=' + title,
    })
  },
  requestCall: function (id) {
    var that = this;
    var data = {
      map: 'applet_mobile_set_record',
      sid: id,
      type: 'mobile'
    };
    console.log(data);
    wx.showLoading({
      title: '加载中',
      mask: true,
      time: 100000
    })
    wx.request({
      url: app.globalData.requestUrl,
      data: data,
      success: function (res) {
        console.log(res.data);
        if (res.data.ec == 200) {
          // app.errorTip(that, res.data.data.msg, 2000);
        } else {
          console.log(res.data)
          // app.errorTip(that, res.data.em, 2000);
        }
      },
      complete: function () {
        wx.hideLoading();
      }
    });
  },
  onShareAppMessage: function () {
    var that = this;
    var title = that.data.title;
    var shareInfo = app.globalData.shareInfo;
    title = shareInfo.shareTitle ? shareInfo.shareTitle : title;
    var cover = shareInfo.shareCover ? shareInfo.shareCover : '';
    app.getPoint(that);
    return {
      title: title,
      imageUrl: cover,
      path: '/pages/telBook/telBook?enterfrom=share'
    }
  }
})
